﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddWorkshopForm : XtraForm
    {
        public AddWorkshopForm()
        {
            InitializeComponent();
            this.Load += AddWorkshopForm_Load;
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            var model = new
            {
                WorkshopCode = textBoxCode.Text,
                WorkshopName = textBoxName.Text,
                WorkshopMsg = textBoxDesc.Text,
                CreatedBy = "wyj"
            };

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };

            using (var client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PostAsync("T2/Workshop/AddWorkshop", content);
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"添加失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private async void AddWorkshopForm_Load(object sender, EventArgs e)
        {
            // 自动生成车间编号
            string today = DateTime.Now.ToString("yyyyMMdd");
            string prefix = $"CJ{today}";
            int maxSerial = 0;
            try
            {
                var handler = new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
                };
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Workshop/GetWorkshop");
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(json);
                        var listToken = jsonObject["pageDatas"] ?? jsonObject["data"] ?? jsonObject["result"];
                        if (listToken != null)
                        {
                            var workshops = JsonConvert.DeserializeObject<List<WorkshopForm.WorkShopModel>>(listToken.ToString());
                            if (workshops != null)
                            {
                                foreach (var item in workshops)
                                {
                                    string code = item.WorkshopCode;
                                    if (!string.IsNullOrEmpty(code) && code.StartsWith(prefix))
                                    {
                                        string serialStr = code.Substring(prefix.Length);
                                        if (int.TryParse(serialStr, out int serial))
                                        {
                                            if (serial > maxSerial) maxSerial = serial;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            string newCode = $"{prefix}{(maxSerial + 1).ToString("D3")}";
            textBoxCode.Text = newCode;
            textBoxCode.Properties.ReadOnly = true;
        }

        private void AddWorkshopForm_Load_1(object sender, EventArgs e)
        {

        }
    }
}